package com.zhangqi.zhxa.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zhangqi.zhxa.R;

/**
 * 下拉刷新的listview
 * @author ZhangQi
 * @date 2016-5-8
 */
public class RefreshListView extends ListView {

    private static final int STATE_PULL_TO_REFRESH=1;//下拉刷新
    private static final int STATE_RELEASE_TO_REFRESH=2;//松开刷新
    private static final int STATE_REFRESHING=3;//正在刷新
    private TextView tvTitle;

    private ImageView ivArrow;//刷新的箭头
    private ProgressBar pbLoading ;//刷新的缓存圈圈

    private RotateAnimation animUp;//箭头转向上的动画
    private RotateAnimation animDown;//箭头转向上的动画

    private int mHeaderViewHeight;
    private View mHeaderView;

    private int startY=-1;//我们通过开始的Y坐标判断移动
    private int endY;//结束的Y坐标

    private int mCurrentState = STATE_PULL_TO_REFRESH;//默认是下拉刷新

    public RefreshListView(Context context) {
        super(context);
        initView();
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        mHeaderView = View.inflate(getContext(), R.layout.list_refresh_header,null);
        this.addHeaderView(mHeaderView);//添加头布局

        //隐藏头布局(1.获取头布局高度，2.设置负paddingTop,布局就会往上走)
        //int height = mHeaderView.getHeight();//此处无法获得高度，因为界面还没有绘制完成

        //绘制之前就要获取布局高度
        mHeaderView.measure(0, 0);//手动测量布局
        mHeaderViewHeight = mHeaderView.getMeasuredHeight();//测量之后的高度
        //隐藏头布局，设置top为负
        mHeaderView.setPadding(0,-mHeaderViewHeight,0,0);

        tvTitle = (TextView) mHeaderView.findViewById(R.id.tv_title);
        //箭头
        ivArrow = (ImageView) mHeaderView.findViewById(R.id.iv_arrow);
        pbLoading= (ProgressBar) mHeaderView.findViewById(R.id.pb_loading);//刷新的缓存圈圈

        initAnim();//初始化动画
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                startY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if(startY==-1){//如果用户按住头条新闻向下滑，会导致listview无法拿到ACTION_DOWN
                    //此时要重新获取startY
                    startY = (int) ev.getY();//这里重新初始化是因为在滚动图片上下拉时的Action_DOWN会被拦截了
                }

                //如果当前正在刷新，就什么都不做了，就是说不能再刷新和松开了
                if(mCurrentState==STATE_REFRESHING){
                    break;//跳出循环，让listview自己处理
                }

                endY = (int) ev.getY();
                int dy = endY-startY;
                if(dy>0 && getFirstVisiblePosition()==0){//向下滑动&当前显示的第一个item，才允许下拉刷新
                    int paddingTop  = dy- mHeaderViewHeight;//计算当前的paddingtop值

                    //根据padding切换状态
                    if(paddingTop>=0 && mCurrentState!=STATE_RELEASE_TO_REFRESH){
                        //切换到松开刷新
                        mCurrentState = STATE_RELEASE_TO_REFRESH;
                        refreshState();
                    }else if(paddingTop<0 && mCurrentState !=STATE_PULL_TO_REFRESH) {
                        //切换到下拉刷新
                        mCurrentState = STATE_PULL_TO_REFRESH;
                        refreshState();
                    }

                    mHeaderView.setPadding(0,paddingTop,0,0);//重新设置投布局paddingtop
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                startY = -1;//起始坐标归零

                if(mCurrentState==STATE_RELEASE_TO_REFRESH){
                    //如果当前是松开刷新，就要切换为正在刷新
                    mCurrentState = STATE_REFRESHING;
                    //显示头布局
                    mHeaderView.setPadding(0,0,0,0);//paddingTop为0时显示
                    refreshState();

                    //下拉刷新回调
                    if(mListener !=null){
                        mListener.onRefresh();
                    }

                }else if(mCurrentState==STATE_PULL_TO_REFRESH){
                    //隐藏头布局
                    mHeaderView.setPadding(0,-mHeaderViewHeight,0,0);//paddingTop为负时显示
                }
                break;
            default:
                break;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 初始化箭头动画
     */
    private void initAnim(){
        animUp = new RotateAnimation(0,-180, Animation.RELATIVE_TO_SELF,
                0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        animUp.setDuration(500);
        animUp.setFillAfter(true);//保持状态

        animDown = new RotateAnimation(-180,0, Animation.RELATIVE_TO_SELF,
                0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        animDown.setDuration(500);
        animDown.setFillAfter(true);//保持状态
    }

    /**
     * 根据当前状态刷新界面
     */
    private void refreshState(){
        switch (mCurrentState){
            case STATE_PULL_TO_REFRESH:
                tvTitle.setText("下拉刷新");
                ivArrow.startAnimation(animDown);
                //隐藏进度条
                pbLoading.setVisibility(View.INVISIBLE);//比用GONE更保险
                ivArrow.setVisibility(VISIBLE);
                break;
            case STATE_RELEASE_TO_REFRESH:
                tvTitle.setText("松开刷新");
                //箭头转到上方
                ivArrow.startAnimation(animUp);
                //隐藏进度条
                pbLoading.setVisibility(View.INVISIBLE);//比用GONE更保险
                break;
            case STATE_REFRESHING:
                tvTitle.setText("正在刷新");
                //显示进度条
                pbLoading.setVisibility(View.VISIBLE);//比用GONE更保险
                ivArrow.clearAnimation();//必须先清除动画，才能隐藏控件
                ivArrow.setVisibility(View.INVISIBLE);//隐藏箭头
                break;
            default:
                break;
        }
    }

    private OnRefreshListener mListener;

    public void setOnRefreshLishListener(OnRefreshListener listener){
        mListener = listener;
    }

    //刷新完成
    public void onRefreshComplete(){
        //隐藏头布局
        mHeaderView.setPadding(0,-mHeaderViewHeight,0,0);//paddingTop为负时显示
        mCurrentState =STATE_PULL_TO_REFRESH;

        //隐藏进度条
        pbLoading.setVisibility(INVISIBLE);
        ivArrow.setVisibility(INVISIBLE);
        tvTitle.setText("下拉刷新");
    }


    /**
     * 下拉刷新的回调接口
     */
    public interface OnRefreshListener{
        //下拉刷新的回调
        public void onRefresh();
    }
}
